<?php
namespace App\Models;

class User extends BaseModel
{
    protected $table = "user";

    const PREFIX = 'user_';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }

    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    /**
     * 字段递减
     */
    public function dec($where, $field, $n)
    {
        return $this->multiWhere($where)->decrement($field, $n);
    }

    public function setUser($id, $data = '')
    {
        $key = self::PREFIX . $id;
        $where['id'] = $id;
        if ($data) {
            $this->up($where, $data);
        }
        $member = $this->getOne(['id' => $id]);
        if ($member) {
            $member = $member->toArray();
        }
        $this->memcache->set($key, $member);
        return $member;
    }

    public function addUser($wxInfo)
    {
        $data['openid'] = $wxInfo['openid'];
        $data['wx_name'] = $wxInfo['nickname'];
        $data['wx_avatar'] = $wxInfo['headimgurl'];
        $data['ip'] = request()->ip();
        $data['last_login_time'] = time();
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $res = $this->add($data);
        if (!$res) {
            return false;
        }
        return $res;
    }

    /**
     * 保存编辑
     */
    public function EditUser($request)
    {
        /*$data['primary_card_no'] = $request['primary_card_no'];
        $data['second_card_no'] = $request['second_card_no'];*/
        $data['wx_name'] = $request['wx_name'];
        $data['true_name'] = $request['true_name'];
        $data['group_id'] = $request['group_id'];
        $data['mobile'] = $request['mobile'];
        //$data['created_at'] = date("Y-m-d", time());
        $data['updated_at'] = date("Y-m-d", time());
        $where['id'] = $request['id'];
        $res = $this->up($where, $data);
        if (!$res) {
            return ['state' => 0, "msg" => "编辑保存失败"];
        }
        return ['state' => 0, "msg" => "编辑保存成功"];
    }

    /**
     * 删除用户
     * @param $request
     * @return array
     */
    public function delUser($request)
    {
        $where['id'] = $request['id'];
        $res = $this->del($where);
        if (!$res) {
            return ['state' => 0, '用户删除失败'];
        }
        return ['state' => 1, '用户删除成功'];
    }

    /**
     * 获取单条数据
     */
    public function getUserById($request)
    {
        $where['id'] = $request['id'];
        $data = $this->getOne($where);
        if (!$data) {
            return ['state' => 0, "msg" => "数据不存在"];
        }
        $data = $data->toArray();
        return ['state' => 1, "msg" => "ok", 'data' => $data];
    }

    public function findUserById($id)
    {
        return $this->getOne(['id'=>$id]);
    }

    /**
     * 获取用户列表
     */
    public function getUserList($request)
    {
        $where = [];
        if ($request['keywords']) {
            if (is_numeric($request['keywords'])) {
                $where['id'] = $request['keywords'];
            } else {
                $where['wx_name'] = ['like', '%' . $request['keywords'] . '%'];
            }
        }
        if ($request['g_id'] != 0) {
            $where['group_id'] = $request['g_id'];
        }

        if ($request['starttime'] && $request['endtime']) {
            $where['created_at'] = ['glt', [['>', $request['starttime']], ['<=', $request['endtime']]]];;
        }
        $order['id'] = "desc";
        $rows = $this->getList($where, '*', $order, 5);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 5);
        }
        return $rows;
    }

    public function getUserManage()
    {
        $headTotal = [];
        $nowData = date("Y-m-d", time());
        $where['created_at'] = $nowData;
        $nowRegUser = $this->getList($where);
        if ($nowData) {
            $nowRegUser = $nowRegUser->toArray();
        }
        $headTotal['nowRegUser'] = count($nowRegUser);
        $uwhere = [];
        $order['id'] = 'desc';
        $user = $this->getList($uwhere, "*", $order, 10);
        if ($user) {
            $user = $user->toArray();
            $user['pageNoList'] = getPageNoList($user['last_page'], request('page', 1), 10);
        }
        $wherelev1['group_id'] = 1;
        $wherelev2['group_id'] = 2;
        $wherelev3['group_id'] = 3;
        $lev1user = $this->getList($wherelev1);
        if ($lev1user) {
            $lev1user = $lev1user->toArray();
        }
        $lev2user = $this->getList($wherelev2);
        if ($lev2user) {
            $lev2user = $lev2user->toArray();
        }
        $lev3user = $this->getList($wherelev3);
        if ($lev3user) {
            $lev3user = $lev3user->toArray();
        }
        $headTotal['regusecont'] = count($user['data']);
        $headTotal['regnor'] = count($lev1user);
        $headTotal['regnor_vip'] = count($lev2user);
        $headTotal['reg_vip'] = count($lev3user);
        $data = [];
        $data = $headTotal;
        $data['user'] = $user;
        return $data;
    }


    public function getUser($mid)
    {
        $key = self::PREFIX . $mid;
        $member = $this->memcache->get($key);
        if (!$member) {
            $member = $this->getOne(['id' => $mid]);
            if ($member) {
                $member = $member->toArray();
            }
            $this->memcache->set($key, $member);
        }
        return $member;
    }

    public function findUser($openid)
    {
        $where['openid'] = $openid;
        $member = $this->getOne($where);
        if ($member) {
            $member = $member->toArray();
        }
        return $member;
    }


    public function wechatLogin($wxInfo,$type=0)
    {
        $data['status'] = 1;
        $openid = $wxInfo['openid'];
        $member = $this->findUser($openid);
        $mid = '';
        if (!$member) {
            if ($wxInfo) {
                $mid = $this->addUser($wxInfo);
            }
        } else {
            $mid = $member['id'];
        }
        $memberData['openid'] = $openid;
        $memberData['last_login_time'] = time();
        if (isset($wxInfo['ip'])) {
            $memberData['ip'] = request()->ip();
        }
        $memberData['updated_at'] = date('Y-m-d H:i:s',time());
        $this->setUser($mid,$memberData);
        $url = url('/').'/home.html?mid='.$mid.'&token='.md5(date('Ymd',time()).'_'.$mid);
        if ($type) {
            $url = url('/').'/member_index.html?mid='.$mid.'&token='.md5(date('Ymd',time()).'_'.$mid);
        }
        Header("Location: $url");
    }

    public function delCache($mid)
    {
        $key = self::PREFIX . $mid;
        $this->memcache->delete($key);
    }





}